package com.arrogames.blondbattle.game.rendering
{
	import ash.core.Engine;
	import ash.core.NodeList;
	import ash.core.System;
	import com.arrogames.blondbattle.game.movement.Motion;
	import com.arrogames.blondbattle.input.KeyPoll;
	import com.arrogames.blondbattle.input.TouchPoll;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.media.Camera;
	import flash.ui.Keyboard;
	
	import com.arrogames.blondbattle.game.EntityCreator;
	import com.arrogames.blondbattle.game.graphics.animation.Destroyable;
	import com.arrogames.blondbattle.game.rendering.Display;
	import com.arrogames.blondbattle.game.movement.Position;
	import com.arrogames.blondbattle.game.rendering.RenderNode;
	
	import starling.display.DisplayObject;
	import starling.display.DisplayObjectContainer;

	import org.as3commons.logging.api.getLogger;
	import org.as3commons.logging.api.ILogger;
	
	public class CameraRenderSystem extends System
	{
	
		private static const logger:ILogger = getLogger(CameraRenderSystem);
	
		public var container : DisplayObjectContainer;
		
		private var cams:NodeList;
		private var camera:CameraNode;
		private var worldViewPort:Rectangle;
		
		public function CameraRenderSystem( 
										container : DisplayObjectContainer, 
										worldViewPort:Rectangle ) {
			this.container = container;
			this.worldViewPort = worldViewPort;
			logger.debug("Instantiated");
		}
		
		override public function addToEngine( engine : Engine ) : void {
			cams = engine.getNodeList(CameraNode);
			if (cams.head == null) {
				cams.nodeAdded.add(cameraAdded);
			} else {
				camera = cams.head;
			}
		}
		
		private function cameraAdded(node:CameraNode):void {
			cams.nodeAdded.remove(cameraAdded);
			camera = node;
		}
		
		override public function update( time : Number ) : void {
			
			var position:Point = camera.position.position;
			
			if (position.x < worldViewPort.x) {
				position.x = worldViewPort.x;
			}
			if (position.x+camera.lens.viewport.width > worldViewPort.width) {
				position.x = worldViewPort.width-camera.lens.viewport.width;
			}
			
			container.x = -position.x;
		}

		override public function removeFromEngine( engine : Engine ) : void
		{
			cams = null;
			camera = null;
		}
	}
}
